/**
 * @file ext-polystar.js
 *
 *
 * @copyright 2010 CloudCanvas, Inc. All rights reserved
 * @copyright 2021 Optimistik SAS, Inc. All rights reserved
 * @license MIT
 *
 */

const name = 'reportdata'

const loadExtensionTranslation = async function (svgEditor) {
  let translationModule
  const lang = svgEditor.configObj.pref('lang')
  try {
    translationModule = await import(`./locale/${lang}.js`)
  } catch (_error) {
    console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
    translationModule = await import('./locale/en.js')
  }
  svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
}

export default {
  name,
  async init() {
    const svgEditor = this
    const { svgCanvas } = svgEditor
    const { ChangeElementCommand } = svgCanvas.history
    const addToHistory = (cmd) => { svgCanvas.undoMgr.addCommandToHistory(cmd) }
    const { $id, $click, $qq } = svgCanvas
    let selElems
    let started
    let newFO,repGroup
    let butTitle = ["|◁", "◁", "▷", "▷|", "☀"]
    let p = {
      x1: 0,
      x2: 0,
      y1: 0,
      y2: 0,
      ws: 80,
      hs: 30,
      col: 0,
      row: 0,
      bw:5,
      bh:5,
      last_col: 0,
      last_row: 0,
      ttArr:["列1","列2","列3","列4","列5","列6"],
      cssstyle: { "font-size": 16, "font-family": svgCanvas.getCurText('font_family') }
    }
    await loadExtensionTranslation(svgEditor)

    const isGecko = navigator.userAgent.includes('Gecko/')
    const setAttrs = (elem, attrs) => {
      if (isGecko) {
        Object.entries(attrs).forEach(([aname, val]) => {
          elem.setAttribute(aname, val)
        })
      } else {
        Object.entries(attrs).forEach(([aname, val]) => {
          const prop = elem[aname]
          if (prop?.constructor === 'SVGLength') {
            prop.baseVal.value = val
          } else {
            elem.setAttribute(aname, val)
          }
        })
      }
    }
    const createLg = (id) => {
      var tmp = `<svg><defs>
        <linearGradient id="lgbut" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stop-color="#7f7f7f"/>
          <stop offset="0.4" stop-color="#fff"/>
          <stop offset="0.6" stop-color="#fff"/>
          <stop offset="1" stop-color="#7f7f7f"/>
        </linearGradient>
        </svg></defs>`
      var lgs = $(tmp).find("defs>*")
      if (svgCanvas.findDuplicateGradient(lgs[0]) == null) {
      }else{
        $(svgCanvas.findDuplicateGradient(lgs[0])).remove()
        
      }
      svgCanvas.findDefs().append(lgs[0]);
    }
    const creatVerticalLine = (p) => {
      var n = p.col + 1
      n = 2 + p.ttArr.length
      var twidth = p.ws * (p.col-1)/p.ttArr.length
      for (var i = 0; i < n; i++) {
        if (i < 2) {
          createSvgLine({ x1: p.x1 + i * p.ws, y1: p.y1, x2: p.x1 + i * p.ws, y2: p.y1 + p.row * p.hs, class:'verticalLine reportdataLine' })
        } else {
          createSvgLine({ x1: p.x1 + p.ws + (i-1) * twidth , y1: p.y1, x2: p.x1 + p.ws + (i-1) * twidth , y2: p.y1 + p.row * p.hs, class:'verticalLine reportdataLine' })
        }
      }
    }
    const createHorizoneLine = (p) => {
      var n = p.row + 1
      for (var i = 0; i < n; i++) {
        createSvgLine({ x1: p.x1, y1: p.y1 + i * p.hs, x2: p.x1 + p.col * p.ws, y2: p.y1 + i * p.hs , class:'horizoneLine reportdataLine'})
      }
    }
    const createSvgLine = (p) => {
      var rect = svgCanvas.addSVGElementsFromJson({
        element: 'line',
        curStyles: false,
        attr: {
          x1: p.x1,
          y1: p.y1,
          x2: p.x2,
          y2: p.y2,
          class: p.class,
          id: svgCanvas.getNextId(),
          'stroke': 'black',
          'stroke-width': 1,
          'stroke-linecap': "round"
        }
      })
      repGroup.append(rect)
    }

    const createRect = (p) => {
      var rect1 = svgCanvas.addSVGElementsFromJson({
        element: 'rect',
        curStyles: false,
        attr: {
          x: p.x,
          y: p.y,
          width: p.width,
          height: p.height,
          class: "reportdataText",
          id: svgCanvas.getNextId(),
          fill: p.fill,
          'stroke': 'red',
          'stroke-width': p.strokeWidth,
          'stroke-linecap': "round"
        }
      })
      repGroup.append(rect1)
    }

    const createG = (id, className) => {
      var g = svgCanvas.addSVGElementsFromJson({
        element: 'g',
        attr: {
          class: className,
          id: id
        }
      })
      return g
    }

    const createButtonRect = (id, className, p, parent, textVal) => {
      var g = createG(id+"g","g_but_class")
      var rect = svgCanvas.addSVGElementsFromJson({
        element: 'rect',
        curStyles: false,
        attr: {
          x: p.x,
          y: p.y,
          width: 2,
          height: 2,
          class: className,
          id: id,
          'stroke': '#cccccc',
          'stroke-width': 2,
          'fill': `url(#lgbut)`
        }
      })
      var text = svgCanvas.addSVGElementsFromJson({
        element: 'text',
        curStyles: true,
        attr: {
          x: p.x + 130 / 2,
          y: p.y + 20 / 1.5,
          class: 'but_text',
          id: id + "_text",
          'stroke-width': 1,
          'font-size': 8,
          'font-family': svgCanvas.getCurText('font_family'),
          'text-anchor': 'middle',
          'xml:space': 'preserve',
          'white-space': 'normal'
        }
      })
      text.textContent = textVal
      g.append(rect)
      g.append(text)
      parent.append(g)
    }

    const AjustGzpaiButtons = (p) => {
      p.bw = Math.abs(p.col * p.ws-5) / 5
      p.bh = 20
      for (var i = 0; i < butTitle.length; i++) {
        var butpos = { x: p.x1 + i * (p.bw + 2), y: p.y1, width: p.bw, height: p.bh }
        setAttrs($id(newFO.id + "_but_" + i), butpos)
        setAttrs($id(newFO.id + "_but_" + i + "_text"), { x: butpos.x + p.bw / 2, y: butpos.y + p.bh / 1.5 })
      }
    }

    const createThreeRect = (p) => {
      var p1 = {x: p.x1,  y: p.y1,width: p.col * p.ws, height: p.row * p.hs,fill:"lightgray" ,strokeWidth:0}
      var p2 = { x: p.x1,y: p.y1,  width: p.col * p.ws, height: p.hs,fill:"lightgreen",strokeWidth:0}
      var p3 = {x: p.x1,y: p.y1 + p.hs,width: p.ws,height: (p.row - 1) * p.hs,fill:"lightgreen",strokeWidth:0}
      createRect(p1)
      createRect(p2)
      createRect(p3)
    }

    const createText = (p) => {
      var text = svgCanvas.addSVGElementsFromJson({
        element: 'foreignObject',
        curStyles: true,
        attr: {
          x: p.x,
          y: p.y,
          width: p.width,
          height: p.height,
          class: p.class,
          id: p.id,
          'fill': "yellow",
          'text-anchor': 'middle',
          'xml:space': 'preserve',
          'stroke': 'none',
          'opacity': 1,
          'color': 'black'
        }
      })
      text.textContent = p.data
      repGroup.append(text)
    }

    const createReportText=(p)=>{
      var twidth = p.ws * (p.col-1)/p.ttArr.length
      for(var row=0;row<p.row;row++){
        var p1 = {
          x: p.x1 + p.ws / 20 ,
          y: p.y1 + p.hs / 6 + row * p.hs,
          width: p.ws * 9 / 10,
          height: p.hs * 5 / 6,
          id:"rptt_0_"+row,
          data:row==0?"序号":row,
          class:'index'
        }
        createText(p1)

        for(var t=0;t<p.ttArr.length;t++){
          var p2 = {
            x: p.x1 + p.ws / 20 + p.ws + twidth*t,
            y: p.y1 + p.hs / 6 + row*p.hs,
            width: twidth* 9 / 10,
            height: p.hs * 5 / 6,
            id:"rptt_1_"+row + "_" +t,
            data:row==0?p.ttArr[t]:"...",
            class:row==0? "tcls":"dcls"
          }
          createText(p2)
        }
      }
    }

    const createreportdata = (p) => {
      var col = Math.floor(Math.abs(p.x2 - p.x1) / p.ws)
      var row = Math.floor(Math.abs(p.y2 - p.y1) / p.hs)
      if (col == 0 || row == 0) {
        return
      }
      p.col = col
      p.row = row
      if (p.col == p.last_col && p.row == p.last_row) {
        return
      }
      $(repGroup).empty()
      var p1 = {...p}
      p1.y1 = p.y1 + p.bh
      createThreeRect(p1)
      creatVerticalLine(p1)
      createHorizoneLine(p1)
      createReportText(p1)
      p.last_col = col
      p.last_row = row
    }

    return {
      name: svgEditor.i18next.t(`${name}:name`),
      // The callback should be used to load the DOM with the appropriate UI items
      callback() {
        // Add the button and its handler(s)
        // Note: the star extension needs to be loaded before the polygon extension
        const fbtitle = `${name}:title`
        const titleStar = `${name}:buttons.0.title`
        const titlePolygon = `${name}:buttons.1.title`
        const buttonTemplate = `
              <se-button id="tool_reportdata" title="${titlePolygon}" src="reportdata.svg">
              </se-button>
          `
        svgCanvas.insertChildAtIndex($qq('.shaps .itemWrap'), buttonTemplate, 8)

        $click($id('tool_reportdata'), () => {
          if (this.leftPanel.updateLeftPanel('tool_reportdata')) {
            svgCanvas.setMode('reportdata')
          }
        })
        $("#tool_reportdata").on("click",".dcls",function(){
          alert("忘记带了解放路卡士大夫")
        })
      },
      mouseDown(opts) {
        if (svgCanvas.getMode() === 'resize') {
          var eles = svgCanvas.getSelectedElements()
          if (eles.length == 1 && eles[0].classList.contains("reportdata")) {
            const e = opts.event
            const {target} = e
            p.x1 = eles[0].getBBox().x
            p.y1 = eles[0].getBBox().y
            p.x2 = eles[0].getBBox().x + eles[0].getBBox().width + 5
            p.y2 = eles[0].getBBox().y + eles[0].getBBox().height
            var lines = $(eles[0]).find(".reportdataLine")
            var length = lines.length;
            p.ws = $(lines[1]).attr("x2") - $(lines[0]).attr("x2");
            p.hs = $(lines[length - 1]).attr("y2") - $(lines[length - 2]).attr("y2")
            newFO = eles[0]
            repGroup = $id(newFO.id + "_excel")
            var ttr = $(newFO).find(".tcls")
            p.ttArr = []
            Array.from(ttr).forEach((elem, i) => {
              p.ttArr.push(elem.textContent)
            })
            console.log('p.ttArrp',p.ttArr)
            started = true
          } else {
            return
          }
        }
        if (svgCanvas.getMode() === 'reportdata') {
          started = true
          p.x1 = opts.start_x
          p.y1 = opts.start_y
          newFO = svgCanvas.addSVGElementsFromJson({
            element: 'g',
            attr: {
              class: 'reportdata ems',
              'doc-type': 'reportdata',
              id: svgCanvas.getNextId()
            }
          })
          var svgId = newFO.id
          repGroup = svgCanvas.addSVGElementsFromJson({
            element: 'g',
            attr: {
              class: 'excel',
              'doc-type': 'reportdata',
              id: svgId+"_excel"
            }
          })
          newFO.append(repGroup)
          createLg(svgId)
          for (var i = 0; i < butTitle.length; i++) {
            createButtonRect(svgId + "_but_" + i, "report_but", { x: p.x1 , y: p.y1 }, newFO, butTitle[i])
          }
          return {
            started: true
          }
        }
        return undefined
      },
      mouseMove(opts) {
        if (!started) {
          return undefined
        }
        const zoom = svgCanvas.getZoom()
        let x = opts.mouse_x / zoom
        let y = opts.mouse_y / zoom
        var eles = svgCanvas.getSelectedElements()
        var doResize = false
        if (svgCanvas.getMode() === 'resize') {
          if (eles.length == 1 && eles[0].classList.contains("reportdata")) {
            doResize = true
            p.x1 = eles[0].getBBox().x
            p.y1 = eles[0].getBBox().y
            if (svgCanvas.getCurrentResizeMode().includes('se')) {
              p.x2 = x+2
              p.y2 = y
            } else if (svgCanvas.getCurrentResizeMode().includes('e')) {
              p.x2 = x+2
            } else if (svgCanvas.getCurrentResizeMode().includes('s')) {
              p.y2 = y
            }else{
              return
            }
          } else {
            return
          }
        }
        if (svgCanvas.getMode() === 'reportdata') {
          p.x2 = x
          p.y2 = y
        }
        if (svgCanvas.getMode() === 'reportdata' || (svgCanvas.getMode() === 'resize' && doResize)) {
          AjustGzpaiButtons(p)
          createreportdata(p)
          if (svgCanvas.getMode() === 'resize') {
            svgCanvas.selectorManager.requestSelector(eles[0]).resize()
            svgCanvas.call('transition', eles[0])
          }
          return {
            started: true
          }
        }
        return undefined
      },
      mouseUp() {
        if (svgCanvas.getMode() === 'reportdata') {
          const keep = p.col >= 1 && p.row >= 1
          return {
            keep,
            element: newFO
          }
        }
        return undefined
      },
      updateReportData(opts){
        if(opts.mode!="reportdata"){
          return
        }
        var data = opts.data;
        //dosomething
      },
    }
  }
}
